import * as path from 'path';
import * as fs from 'fs';
import * as config from 'config';
import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  UploadedFiles,
  Body,
  Get,
  Query,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { createHmac } from 'node:crypto';
import { FileService } from './file.service';

@Controller('file')
export class FileController {
  constructor(private readonly fileService: FileService) {}
  @Post('upload')
  @UseInterceptors(FilesInterceptor('file'))
  uploadFiles(@UploadedFiles() files: Express.Multer.File, @Body() body) {
    const fullPath = path.join(
      __dirname,
      `../../../files/${new Date().getFullYear()}/${new Date().getMonth()}`,
    );
    const exist = fs.existsSync(fullPath);
    if (!exist) {
      fs.mkdirSync(fullPath, { recursive: true });
    }
    const resultPathArr = [];
    for (const key in files) {
      const res = files[key];
      const dir = path.resolve(fullPath, res.originalname);
      fs.writeFileSync(dir, res.buffer);
      const fingerprint = this.generateUniVal();
      const resultPath = `/files/${new Date().getFullYear()}/${new Date().getMonth()}/${
        res.originalname
      }`;
      resultPathArr.push({ resultPath, fingerprint });
      this.fileService.setFinger(resultPath, fingerprint);
    }
    return resultPathArr;
  }

  @Get('download')
  async download(@Query() query) {
    return await this.fileService.getFile(query.fingerPrint);
  }
  generateUniVal() {
    const val = `${Math.random()
      .toString(36)
      .substr(2)}${new Date().getTime()}`;
    const hash = createHmac('sha256', val)
      .update(config.get('secretOrKey'))
      .digest('hex');
    return hash;
  }
}
